'use strict';

var Model = require('../../model/mongo/shop.js');
var debug = require('debug')('shop');
let fout = require('../../common/function.js').formatOutput;

function MongoDao() {
    let self = this instanceof MongoDao ? this : new MongoDao();
    return self;
}
module.exports = MongoDao;
let theProto = MongoDao.prototype;
var selector = {
    __v: 0
};

/**
 {
  "name": "shop-test",
  "address": "天河区天河路208号粤海喜来登酒店8楼",
  "tel": "020-66822580",
  "desc": "一家店",
  "imgUrl": ["https://www.baidu.com/img/bdlogo.png"],
  "webUrl":"https://www.baidu.com/",
  "districts": [{"_id":"xxx","pId":"xxx","name":"xxx"}],
  "loc": [23.13268,113.322],
  "cates": ["美容","美发"]
}
 * @param json
 * @returns {*}
 */
theProto.save = function*(json) {
    console.log(json);
    console.log('-----------------');
    var entity = {
        userId: json.userId || null,
        name: json.name,
        address: json.address,
        tel: json.tel,
        desc: json.desc,
        imgUrl: json.images_url || [],
        webUrl: json.web_url || [],
        districts: json.districts,
        cates: json.cates || []
    };
    if (json.loc) {
        entity.loc = {type: "Point", coordinates: json.loc}
    }
    entity = new Model(entity);
    console.log(entity);

    var result = yield entity.save();
    return fout(0, null, result);
};

// 查询
theProto.findById = function*(id) {
    debug('findById', id);
    let errCode = 0;
    let errMsg = null;
    let data = null;
    try {
        var result = yield Model.findOne({_id: id}, selector);
        errMsg = result.errors;
        data = result._doc;
    } catch (e) {
        errMsg = e.toString();
    }

    if (errMsg) {
        errCode = 10401;
        errMsg = 'shop: id not exists,' + errMsg;
        return fout(errCode, errMsg);
    }
    return fout(errCode, errMsg, data);
};


theProto.findByIdList = function*(idList) {
    debug('findByIdList', idList);
    var result = yield Model.find({_id: {$in: idList}});
    result = result.map(function (item) {
        return item._doc;
    });
    console.log(result);
    return fout(0, null, result);
};

/**
 * cannot return the doc that updated
 * @param idList
 * @param cates
 * @returns {{errCode: *, errMsg: *, result: *}}
 */
theProto.updateCates = function*(idList, cates) {
    debug('updateCates', idList, cates);
    let query = {_id: {$in: idList}};
    //let query = {_id: idList[0]};
    let update = {$addToSet: {cates: {$each: cates}}};
    let option = {'new': true, multi: true};
    var result = yield Model.update(query, update, option);
    console.log(result);
    return fout(0, null, result);
};
